package battleship.cxbr;

import java.util.ArrayList;

import battleship.emss.*;

public class DefendContext extends Context
{
	protected int cx;
	protected int cy;
	protected int sx;
	protected int sy;
	protected double st;
	
	public DefendContext(String n,CxBRAgent a)
	{
		super(n,a);
	}
	
	//How to get here from above
	public double ParentRule(double Time)
	{
		//to progress from Protect to Defend, must detect a sub
		for(int i=0;i<Agent.detectedStatus.size();i++)
		{
			Status tmpStatus=Agent.detectedStatus.get(i);
			//not on team and a sub
			if(tmpStatus.team!=Agent.status.team && tmpStatus.type==Agent.SUB)
			{
				st=Time;
			}
		}
		
		//defend for at least a minute
		if(Time-st<1200)
		{
			return 1.0;
		}
		return 0.0;
	}

	//How to get here from side
	public double SiblingRule(double Time)
	{
		return 0.0;
	}
	
	//Things to do when just entering
	public void Initialize(double Time)
	{

	}

	
	//What do actually do
	public void Action(double Time)
	{
		Agent.status.status=Name;
		Agent.actions.clear();
		
		Agent.status.status+=" Defending";

		//detected others
		for(int i=0;i<Agent.detectedStatus.size();i++)
		{
			Status tmpStatus=Agent.detectedStatus.get(i);
			//on my team, and a carrier
			
			if(tmpStatus.team==Agent.status.team && tmpStatus.type==Agent.CARRIER)
			{
				cx=tmpStatus.x;
				cy=tmpStatus.y;
			}

			//not on team and a sub
			if(tmpStatus.team!=Agent.status.team && tmpStatus.type==Agent.SUB)
			{
				sx=tmpStatus.x;
				sy=tmpStatus.y;
			}
		}
		
		//get in the middle of carrier and sub
		int dx,dy;
		dx=(cx+sx)/2;
		dy=(cy+sy)/2;

		//driving blind
		if(Math.sqrt(Math.pow(Agent.status.x-dx,2)+Math.pow(Agent.status.y-dy,2))>5)
		{
			Agent.actions.add(new Move(Agent.status.x,Agent.status.y,dx,dy,12));
		}
		else
		{
			Agent.actions.add(new Move(Agent.status.x,Agent.status.y,dx,dy,3));
		}
		//already have a sub, and close fire
		if(Math.sqrt(Math.pow(Agent.status.x-sx,2)+Math.pow(Agent.status.y-sy,2))<5)
		{
			Agent.actions.add(new Fire(Agent.status.x,Agent.status.y,sx,sy));
		}
		
		
		Agent.incomingMessages.clear();
		
				
		return;
	}
	
}

